<template>
	<div class='divchart' style='background-color:#0e182e;'>
		
		<!--  #ifdef  H5 -->
		<div>
			<div class='kline' id="kline" ref='kline'></div>
		</div>
		<!--  #endif -->
		
		<!--  #ifndef  H5 -->
		<view>
			<canvas id="kline2" canvas-id='kline2' class='kline2' v-bind:style="{width: ChartWidth+'px', height: ChartHeight+'px'}" 
			  @touchstart="KLineTouchStart" @touchmove='KLineTouchMove' @touchend='KLineTouchEnd' ></canvas>
		</view>
		<!--  #endif -->
		
		<div class="button-sp-area">
			<button class="mini-btn" type="default" size="mini" @click="ChangePeriod(-1)">分时</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangePeriod(0)">日线</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangePeriod(1)">周线</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangePeriod(4)">1分钟</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangePeriod(6)">15分钟</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeDepthChart()">深度图</button>
		</div>
		
		<div class="button-sp-area">
			<button class="mini-btn" type="default" size="mini" @click="ChangeSymbol('btcusdt')">btcusdt</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeSymbol('ethusdt')">ethusdt</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeIndex(0, 'EMPTY')">EMPTY</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeIndex(1, 'MACD')">MACD</button>
		</div>
		
	</div>
</template>

<script>
// #ifdef H5	
import HQChart from '@/uni_modules/jones-hqchart2/js_sdk/umychart.uniapp.h5.js'
// #endif

// #ifndef H5
import {JSCommon} from '@/uni_modules/jones-hqchart2/js_sdk/umychart.wechat.3.0.js'
import {JSCommonHQStyle} from '@/uni_modules/jones-hqchart2/js_sdk/umychart.style.wechat.js'
import {JSConsole} from '@/uni_modules/jones-hqchart2/js_sdk/umychart.console.wechat.js'

//禁用日志
JSConsole.Complier.Log=()=>{ };
JSConsole.Chart.Log=()=>{ };
// #endif

var pako = require('pako');

function DefaultData() { }

DefaultData.GetKLineOption = function () 
{
    let data = 
    {
        Type: '历史K线图', 
		//Type: '历史K线图横屏',
        
        Windows: //窗口指标
        [
            {Index:"MA",Modify: false, Change: false, Close:false}, 
            {Index:"VOL",Modify: false, Change: false,Close:false},
			{Index:"MACD2",Modify: false, Change: false,Close:false}
        ], 
 
		IsAutoUpdate:false,           //是自动更新数据(不自动更新由外部更新)
        IsApiPeriod:true,             //使用Api计算周期
        IsCorssOnlyDrawKLine:true,
        CorssCursorTouchEnd:true,
 
        Border: //边框
        {
            Left:   1,
            Right:  1, //右边间距
            Top:    25,
            Bottom: 25,
        },
 
        KLine:
        {
            Right:0,                            //复权 0 不复权 1 前复权 2 后复权
            Period:0,                           //周期: 0 日线 1 周线 2 月线 3 年线 
            PageSize:30,
            IsShowTooltip:false,
			DrawType:0,
        },
		
		KLineTitle:
		{
			IsShowName:false,
			IsShowSettingInfo:false,
		},
		
		Frame:  //子框架设置
		[
			{   
				SplitCount:3,IsShowLeftText:false, SplitType:1,
				Custom: [ { Type:0, Position:'right' } ]
			},

			{SplitCount:2,IsShowLeftText:false, SplitType:1 },
			{SplitCount:2,IsShowLeftText:false}
		],
		
		ExtendChart:
		[
			{Name:'KLineTooltip' },	//开启手机端tooltip
		], 
        
    };
 
    return data;
}

DefaultData.GetMinuteOption = function () 
{
    let data = 
    {
        Type: '历史K线图', 
		//Type: '历史K线图横屏',
        
        Windows: //窗口指标
        [
            {Index:"EMPTY",Modify: false, Change: false, Close:false, TitleHeight:0 }, 
            {Index:"VOL",Modify: false, Change: false,Close:false},
        ], 
 
		IsAutoUpdate:false,           //是自动更新数据(不自动更新由外部更新)
        IsApiPeriod:true,             //使用Api计算周期
        IsCorssOnlyDrawKLine:true,
        CorssCursorTouchEnd:true,
 
        Border: //边框
        {
            Left:   1,
            Right:  1, //右边间距
            Top:    25,
            Bottom: 25,
        },
 
        KLine:
        {
            Right:0,                            //复权 0 不复权 1 前复权 2 后复权
            Period:4,                           //周期: 0 日线 1 周线 2 月线 3 年线 
            PageSize:60,
            IsShowTooltip:false,
			DrawType:4,
        },
		
		KLineTitle:
		{
			IsShowName:false,
			IsShowSettingInfo:false,
		},
		
		Frame:  //子框架设置
		[
			{   
				SplitCount:3,IsShowLeftText:false, SplitType:1,
				Custom: [ { Type:0, Position:'right' } ]
			},

			{SplitCount:2,IsShowLeftText:false, SplitType:1 },
			{SplitCount:2,IsShowLeftText:false}
		],
		
		ExtendChart:
		[
			{Name:'KLineTooltip' },	//开启手机端tooltip
		], 
        
    };
 
    return data;
}
 
DefaultData.GetDepthOption=function()
{
	var option=
	{
		Type:'深度图',   //创建图形类型
		EnableZoomUpDown:
		{
		//Wheel:false,
		//Keyboard:false,
		//Touch:false,
		},

		Symbol:'BTCBUSD.bit',
		IsAutoUpdate:false,       //是自动更新数据
		AutoUpdateFrequency:10000,   //数据更新频率
		//CorssCursorTouchEnd:true,
		EnableScrollUpDown:true,

		MaxVolRate:1.2,

		CorssCursorInfo: { HPenType:0, VPenType:1, IsShowTooltip:true },

		Listener:
		{
		//KeyDown:false,
		//Wheel:false
		},
		
		SplashTitle:"下载数据 ......",
		Language:"EN",

		Border: //边框
		{
		Left:1,         //左边间距
		Right:1,       //右边间距
		Bottom:25,      //底部间距
		Top:1           //顶部间距
		},

		//框架设置
		Frame: { SplitCount:2, IsShowLeftText:false , XLineType:3, XSplitCount:2 },

	};

	return option;
}
 
var KLINE_CHART_TYPE =
{
	KLINE_ID:1,   		//K线图
	MINUTE_KLINE_ID:2  //K线面积图
};

var g_KLine={ JSChart:null };

export default 
{
	data() 
	{
		let data=
		{
			Symbol:'btcusdt.BIT', 
			OriginalSymbol:'btcusdt',
			ChartWidth:300,
			ChartHeight:600,
			KLine:
			{
				Option:DefaultData.GetKLineOption(), 
			},
			
			WSUrl:'wss://www.huobi.com/-/s/pro/ws',	//火币api地址, 需要根据火币网经常调整. 会经常变(https://www.huobi.br.com/en-us/exchange/btc_usdt/)
			SocketOpen:false,
			LastSubString:null,     //最后一个订阅的数据
			
			Update:
			{
				EnableLimit:false,		//更新是否限速
				LastUpdateTime:null,
				Frequency:5000,		//更新频率
				Cache:null,
			}
		};
		
		return data;
	},
	
	name:'KLineChart',
	
	onLoad() 
	{
		
	},
	
	onReady()
	{	
		console.log("[KLineChart::onReady]");
		this.$nextTick(()=>
		{
			// #ifndef H5
			this.OnSize();
			this.CreateKLineChart(KLINE_CHART_TYPE.KLINE_ID, 4); 
			// #endif
		});
	},
	
	onShow()
	{
		uni.getSystemInfo({
		    success:  (res) =>
			{
				var width=res.windowWidth;
				var height=res.windowHeight;
		        this.ChartWidth=width;
				this.ChartHeight=height-130;
				this.$nextTick(()=>
				{
					this.InitalHQChart();
					this.OnSize();
					this.CreateKLineChart(KLINE_CHART_TYPE.KLINE_ID, 4); 
				})
		    }
		});
	},
	
	onHide()
	{
		if(this.SocketOpen)
		{
			uni.closeSocket();
			this.SocketOpen=false;
		}
		
		this.ClearChart();
	},
	
	onUnload()
	{
		if(this.SocketOpen)
		{
			uni.closeSocket();
			this.SocketOpen=false;
		}
		
		this.ClearChart();
	},
	
	methods: 
	{
		//对外接口
		ChangePeriod(period)  //周期切换
		{
			if(period==-1)
			{
				if (g_KLine.JSChart.KLineType!=KLINE_CHART_TYPE.MINUTE_KLINE_ID)
				{
					this.ClearChart();
					this.CreateKLineChart(KLINE_CHART_TYPE.MINUTE_KLINE_ID,4);
				}
			}
			else
			{
				if (g_KLine.JSChart.KLineType==KLINE_CHART_TYPE.KLINE_ID)
				{
					g_KLine.JSChart.ChangePeriod(period);
				}
				else
				{
					this.ClearChart();
					this.CreateKLineChart(KLINE_CHART_TYPE.KLINE_ID,period);
				}
			}
			
		},
		
		ChangeSymbol(symbol)   //切换股票
		{
			if (this.OriginalSymbol==symbol) return;

			this.OriginalSymbol=symbol;
			this.Symbol=symbol+'.BIT';
			g_KLine.JSChart.ChangeSymbol(this.Symbol);
		},
		
		ChangeIndex(index, name)
		{
			g_KLine.JSChart.ChangeIndex(index, name);
		},
				
		OnSize()
		{
			// #ifdef H5
			this.OnSize_h5();
			// #endif
		},
		
		OnSize_h5()
		{
			var chartHeight = this.ChartHeight;
			var chartWidth = this.ChartWidth;
			 
			var kline=this.$refs.kline;
			kline.style.width=chartWidth+'px';
			kline.style.height=chartHeight+'px';
			if (g_KLine.JSChart) g_KLine.JSChart.OnSize();
		},
		
		InitalHQChart()
		{
			// #ifdef H5
			HQChart.MARKET_SUFFIX_NAME.GetBITDecimal=this.GetBITDecimal;
			var blackStyle=HQChart.HQChartStyle.GetStyleConfig(HQChart.STYLE_TYPE_ID.BLACK_ID);
			this.SetHQChartStyle(blackStyle);
			HQChart.JSChart.SetStyle(blackStyle);
			
			// #endif
			
			// #ifndef H5
			JSCommon.MARKET_SUFFIX_NAME.GetBITDecimal=this.GetBITDecimal;
			var blackStyle=JSCommonHQStyle.GetStyleConfig(JSCommonHQStyle.STYLE_TYPE_ID.BLACK_ID);
			this.SetHQChartStyle(blackStyle);;
			JSCommon.JSChart.SetStyle(blackStyle);	
			
			// #endif
		},
		
		//设置图形颜色
		SetHQChartStyle(blackStyle)
		{
			blackStyle.BGColor='rgb(14,24,46)';                 //背景
			blackStyle.TooltipPaint.BGColor="rgba(14,24,46,0.8)";			//tooltip背景色
			blackStyle.FrameTitleBGColor='rgb(14,24,46)';       //指标标题背景
			blackStyle.FrameSplitTextColor='rgb(101,117,138)';  //刻度颜色
		
			//K线颜色
			blackStyle.UpBarColor='rgb(37,175,142)';
			blackStyle.UpTextColor= blackStyle.UpBarColor;
			blackStyle.DownBarColor='rgb(210,73,99)';
			blackStyle.DownTextColor=blackStyle.DownBarColor;
			//平盘
			blackStyle.UnchagneBarColor=blackStyle.UpBarColor;
			blackStyle.UnchagneTextColor=blackStyle.UpBarColor;
		
			//指标线段颜色
			blackStyle.Index.LineColor[0]='rgb(88,106,126)';    
			blackStyle.Index.LineColor[1]='rgb(222,217,167)';
			blackStyle.Index.LineColor[2]='rgb(113,161,164)';
		
			//最新价格刻度颜色
			blackStyle.FrameLatestPrice.UpBarColor='rgb(37,175,142)';
			blackStyle.FrameLatestPrice.DownBarColor='rgb(210,73,99)';
			blackStyle.FrameLatestPrice.UnchagneBarColor=blackStyle.FrameLatestPrice.UpBarColor;
			
			blackStyle.Frame.XBottomOffset=2;
			
			//blackStyle.Minute.PriceColor='rgb(255,255,255)';
		},
		
		GetBITDecimal(symbol)
		{
			var lowerSymbol=symbol.toLowerCase();
			if (lowerSymbol=="ethusdt.bit" || lowerSymbol=="btcusdt.bit") return 2;
			
			return 2;
		},
		
		ClearChart()
		{
			if (g_KLine.JSChart)
			{
				g_KLine.JSChart.ChartDestory();
				g_KLine.JSChart=null;
			}
		
			// #ifdef H5
			var divKLine=document.getElementById('kline');
			while (divKLine.hasChildNodes()) 
			{
				divKLine.removeChild(divKLine.lastChild);
			}　
			// #endif
		},
				
		CreateKLineChart_h5(klineType, period)  //创建K线图
		{
		    if (g_KLine.JSChart) return;
			
			//var blackStyle=HQChart.HQChartStyle.GetStyleConfig(HQChart.STYLE_TYPE_ID.BLACK_ID);
			//HQChart.JSChart.SetStyle(blackStyle);
			//this.$refs.kline.style.backgroundColor=blackStyle.BGColor;	//div背景色设置黑色
						
		    this.KLine.Option.Symbol=this.Symbol;
		    let chart=HQChart.JSChart.Init(this.$refs.kline);
			
			if (klineType==KLINE_CHART_TYPE.MINUTE_KLINE_ID)
			{
				this.KLine.Option=DefaultData.GetMinuteOption();
			}
			else
			{
				klineType=KLINE_CHART_TYPE.KLINE_ID;
				this.KLine.Option=DefaultData.GetKLineOption();
			}
			
			this.KLine.Option.NetworkFilter=this.NetworkFilter;
			this.KLine.Option.Symbol=this.Symbol;
			this.KLine.Option.KLine.Period=period;
			
		    chart.SetOption(this.KLine.Option);
		    g_KLine.JSChart=chart;
			g_KLine.JSChart.KLineType=klineType;
		},
		
		CreateKLineChart_app(klineType,period)
		{
			if (g_KLine.JSChart) return;
			
			let element = new JSCommon.JSCanvasElement();
			// #ifdef APP-PLUS
			element.IsUniApp=true;	//canvas需要指定下 是uniapp的app
			// #endif
			element.ID = 'kline2';
			element.Height = this.ChartHeight;  //高度宽度需要手动绑定!!
			element.Width = this.ChartWidth;
			
			//var blackStyle=JSCommonHQStyle.GetStyleConfig(JSCommonHQStyle.STYLE_TYPE_ID.BLACK_ID);
			//JSCommon.JSChart.SetStyle(blackStyle);
					
			g_KLine.JSChart = JSCommon.JSChart.Init(element);
			if (klineType==KLINE_CHART_TYPE.MINUTE_KLINE_ID) 
			{
				this.KLine.Option=DefaultData.GetMinuteOption();
			}
			else
			{
				klineType=KLINE_CHART_TYPE.KLINE_ID;
				this.KLine.Option=DefaultData.GetKLineOption();
			}
			this.KLine.Option.NetworkFilter=(data, callback)=>{ this.NetworkFilter(data, callback); };
			this.KLine.Option.Symbol=this.Symbol;
			this.KLine.Option.IsClickShowCorssCursor=true;
			this.KLine.Option.IsFullDraw=true; 	//每次手势移动全屏重绘
			this.KLine.Option.KLine.Period=period;
			g_KLine.JSChart.SetOption(this.KLine.Option);
			g_KLine.JSChart.KLineType=klineType;
		},
		
		CreateKLineChart(klineType, period)
		{
			this.Update.Cache=null;
			
			// #ifdef H5
			this.CreateKLineChart_h5(klineType,period);
			// #endif
			
			// #ifndef H5
			this.CreateKLineChart_app(klineType,period);
			// #endif
		},
		
		CreateDepthChart()
		{
			this.Update.Cache=null;
			
			// #ifdef H5
			this.CreateDepthChart_h5();
			// #endif
			
			// #ifndef H5
			this.CreateDepthChart_app();
			// #endif
		},
		
		CreateDepthChart_h5()
		{
			if (g_KLine.JSChart) return;
			
			let chart=HQChart.JSChart.Init(this.$refs.kline);
			
			var option=DefaultData.GetDepthOption();
			option.Symbol=this.Symbol;
			option.NetworkFilter=this.NetworkFilter;
			chart.SetOption(option);
			g_KLine.JSChart=chart;
		},
		
		CreateDepthChart_app()
		{
			if (g_KLine.JSChart) return;
			
			var element = new JSCommon.JSCanvasElement();
			// #ifdef APP-PLUS
			element.IsUniApp=true;	//canvas需要指定下 是uniapp的app
			// #endif
			element.ID = 'kline2';
			element.Height = this.ChartHeight;  //高度宽度需要手动绑定!!
			element.Width = this.ChartWidth;
			
			//var blackStyle=JSCommonHQStyle.GetStyleConfig(JSCommonHQStyle.STYLE_TYPE_ID.BLACK_ID);
			//JSCommon.JSChart.SetStyle(blackStyle);
					
			var chart = JSCommon.JSChart.Init(element);
			var option=DefaultData.GetDepthOption();
			option.Symbol=this.Symbol;
			option.IsFullDraw=true; 	//每次手势移动全屏重绘
			option.NetworkFilter=this.NetworkFilter;
			chart.SetOption(option);
			g_KLine.JSChart=chart;
		},
		
		ChangeDepthChart()
		{
			if (g_KLine.JSChart && g_KLine.JSChart.JSChartContainer.ClassName=="DepthChartContainer") return;
			
			this.ClearChart();
			this.CreateDepthChart();
		},
		
		NetworkFilter(data, callback)
		{
			console.log('[KLineChart::NetworkFilter] data', data);
			switch(data.Name)
			{
				case 'KLineChartContainer::ReqeustHistoryMinuteData':   //分钟全量数据下载
					this.RequestHistoryMinuteData(data, callback);
					break;
				case 'KLineChartContainer::RequestFlowCapitalData':     //数字货币不会调用
					this.RequestFlowCapitalData(data, callback);
					break;
				case 'KLineChartContainer::RequestHistoryData':         //日线全量数据下载
					this.RequestHistoryData(data,callback);
					break;
					
				case "DepthChartContainer::RequestDepthData":
				    this.RequestDepthData(data, callback);
				    break;
			}
		},
		
		//////////////////////////////////////////////////////
		//WS
		//心跳包
		SendWSHeartMessage()
		{
			if (this.SocketOpen)
			{
				var pong = {'pong': new Date().getTime()};
				var message=JSON.stringify(pong);
				uni.sendSocketMessage({data:message});
			}
		},

		//取消订阅上一次的信息
		SendUnSubscribeMessage()
		{
			if (!this.LastSubString || !this.SocketOpen)  return;
 
			var message=JSON.stringify({unsub:this.LastSubString}); //取消上次订阅的信息
			uni.sendSocketMessage({data:message});
			this.LastSubString=null;    //清空最后一个订阅信息
		},
		
		RequestWSData(data, recvCallback)
		{
			if (!this.SocketOpen) 
			{
				uni.connectSocket( {url:this.WSUrl} );//创建连接

				uni.onSocketOpen((event)=>
				{
					this.SocketOpen=true;
					console.log(event);
					var message=JSON.stringify(data.SendData);
					uni.sendSocketMessage({data:message});
					if (data.SendData.sub) this.LastSubString=data.SendData.sub;
				});
			}
			else
			{
				this.SendUnSubscribeMessage();
				var message=JSON.stringify(data.SendData);
				uni.sendSocketMessage({data:message});
				if (data.SendData.sub) this.LastSubString=data.SendData.sub;    //保存最后一个订阅信息
			}

			uni.onSocketMessage((event)=>
			{ 
				let ploydata = new Uint8Array(event.data);
				let msg = pako.inflate(ploydata, {to: 'string'});
				//console.log("[KLineChart::RequestWSData] recv ", msg);
				var recvData=JSON.parse(msg);
				if (recvData.ping)
				{
					this.SendWSHeartMessage();  //回复服务器心跳包
				}
				else if (recvData.unsubbed) //取消订阅成功
				{

				}
				else if (recvData.subbed)   //订阅成功 
				{

				}
				else
				{
					recvCallback(recvData, data); 
				}
			});

			uni.onSocketError((event)=>
			{
				console.log(event);
			});
			
		},
		
		//生成请求数据
		GeneratePostData(symbol, period)
		{
			//1min, 5min, 15min, 30min, 60min,4hour,1day,1week, 1mon
			var MAP_PERIOD=new Map([
				[4,'1min'],
				[5,'5min'],
				[6,"15min"],
				[0,'1day'],
				[1,'1week'],
				[2,'1mon'],
			]);

			var strPeriod=MAP_PERIOD.get(period);

			var reqData=
			{
				req: `market.${symbol}.kline.${strPeriod}`,
				symbol: symbol,
				period: strPeriod
			};

			var subData=
			{
				sub: `market.${symbol}.kline.${strPeriod}`,
				symbol: symbol,
				period: strPeriod
			};

			return { Req:reqData ,Sub:subData };
		},

		//请求分钟历史数据
		RequestHistoryMinuteData(data, callback)  
		{
			data.PreventDefault=true;
			this.Update.Cache=null;
			var symbol=data.Request.Data.symbol;
			var period=data.Self.Period;    //周期

			var postData=this.GeneratePostData(this.OriginalSymbol,period);

			var obj={ SendData:postData.Req , Symbol:symbol, OriginalSymbol:this.OriginalSymbol, Period:period, Callback:callback };
this.RecvHistoryMinuteData({},obj);
			// this.RequestWSData(obj, (recvData,data)=>{ this.RecvHistoryMinuteData(recvData,data); });
		},
		
		//接收历史分钟数据
		async RecvHistoryMinuteData(recvData, data)   
		{
			// if (recvData.rep!=data.SendData.req) return;

			var hqChartData={code:0, data:[]};
			hqChartData.symbol=data.Symbol;
			hqChartData.name=data.OriginalSymbol;
const res = await this.$H.post('/api/v1/klineMarket',true,{
							   symbol:"BTC/USDT",
							   period:"1min",
							   from:1692837557,
							   to:1692884378
							   
			})
			if (res.data.data.data)
			{
				var yClose=null; //前收盘
				for(var i in res.data.data.data)
				{
					var item=res.data.data.data[i];
console.log(i)
					//时间戳转换
					var dateTime = new Date();
					dateTime.setTime(item.time);
					var date=dateTime.getFullYear()*10000+(dateTime.getMonth()+1)*100+dateTime.getDate();
					var time=dateTime.getHours()*100+dateTime.getMinutes();

					var newItem=[ date,yClose, item.open, item.high, item.low, item.close, item.amount, null, time ];

					yClose=item.close;
					hqChartData.data.push(newItem);
				}
			}
			
			// #ifdef H5
			data.Callback(hqChartData);
			// #endif
			
			// #ifndef H5
			data.Callback({data: hqChartData});
			// #endif
			
			
			this.SubscribeMinuteRealtimeData(data);
		},
		
		//订阅最新分钟K线数据
		SubscribeMinuteRealtimeData(data)   
		{
			//订阅最新数据
			var postData=this.GeneratePostData(data.OriginalSymbol,data.Period);
			var obj={SendData:postData.Sub, Symbol:data.Symbol, OriginalSymbol:data.OriginalSymbol, Period:data.Period };

			this.RequestWSData(obj, (recvData,data)=>{ this.RecvMinuteRealtimeData(recvData,data); });
		},
		
		RecvMinuteRealtimeData(recvData,data)
		{
			 console.log("___________________________")
			if (recvData.ch!=data.SendData.sub) return;
			if (!g_KLine.JSChart) return;
console.log("+++++++++++++++++++++++++++++++++++")
			var internalChart=g_KLine.JSChart.JSChartContainer;
			var period=internalChart.Period;
			// if (symbol!=data.Symbol || period!=data.Period) return;
console.log("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
			var hqChartData={code:0, data:[], ver:2.0}; //更新数据使用2.0版本格式
			hqChartData.symbol=data.Symbol;
			hqChartData.name=data.OriginalSymbol;

			//TODO:把recvData => hqchart内部格式 格式看教程
			//HQChart使用教程30-K线图如何对接第3方数据15-轮询增量更新1分钟K线数据

			var item=recvData.tick;
           console.log("**********recvData********************")
			console.log(item)
			console.log(recvData.tick)
			 console.log("**********recvData********************")
			var dateTime = new Date();
			dateTime.setTime(item.id*1000);
			var date=dateTime.getFullYear()*10000+(dateTime.getMonth()+1)*100+dateTime.getDate();
			var time=dateTime.getHours()*100+dateTime.getMinutes();
			var newItem=[ date,null, item.open, item.high, item.low, item.close, item.amount, null, time ];
			
			if (this.Update.EnableLimit)	//是否启动缓存定时更新，降低刷新频率
			{
				if (!this.Update.Cache)
				{
					this.Update.Cache={Data:[newItem]};
				}
				else
				{
					var cache=this.Update.Cache;
					var item=cache.Data[cache.Data.length-1];
					if (item[0]==newItem[0] && item[8]==newItem[8])
						cache.Data[cache.Data.length-1]=newItem;
					else 
						cache.Data.push(newItem)
				}
				
				var bUpdate=true;
				if (this.Update.LastUpdateTime)
				{
					var now=Date.now();
					if (now-this.Update.LastUpdateTime<this.Update.Frequency)	//15s更新一次界面
						bUpdate=false;
				}
				
				if (!bUpdate) return;	//不更新
				
				hqChartData.data=this.Update.Cache.Data;
				this.Update.Cache=null;
				this.Update.LastUpdateTime=Date.now();
			}
			else
			{
				console.log("**********newItem********************")
				console.log(newItem)
				
				console.log("**********newItem********************")
				hqChartData.data.push(newItem);
			}
			
			// #ifdef H5
			internalChart.RecvMinuteRealtimeData(hqChartData);
			// #endif
			
			// #ifndef H5
			internalChart.RecvMinuteRealtimeData({data: hqChartData});
			// #endif
			
		},
		
		
		//日K数据下载
        RequestHistoryData(data,callback) 
        {
            data.PreventDefault=true;
			this.Update.Cache=null;
            var symbol=data.Request.Data.symbol;
            var period=data.Self.Period;    //周期
            var postData=this.GeneratePostData(this.OriginalSymbol,period);

            var obj={ SendData:postData.Req , Symbol:symbol, OriginalSymbol:this.OriginalSymbol, Period:period, Callback:callback };

            this.RequestWSData(obj, (recvData,data)=>{ this.RecvHistoryData(recvData,data); });
        },

        RecvHistoryData(recvData,data)  //接收到日线数据 转化成hqchart格式数据
        {
            if (recvData.rep!=data.SendData.req) return;

            var hqChartData={code:0, data:[]};
            hqChartData.symbol=data.Symbol;
            hqChartData.name=data.OriginalSymbol;

            if (recvData.data)
            {
				//console.log("[RecvHistoryData] recvData.data",recvData.data);
                var yClose=null; //前收盘
                for(var i in recvData.data)
                {
                    var item=recvData.data[i];

                    //时间戳转换
                    var dateTime = new Date();
                    dateTime.setTime(item.id*1000);
                    var date=dateTime.getFullYear()*10000+(dateTime.getMonth()+1)*100+dateTime.getDate();
                    var time=dateTime.getHours()*100+dateTime.getMinutes();

                    var newItem=[ date,yClose, item.open, item.high, item.low, item.close, item.amount, null];

                    yClose=item.close;
                    hqChartData.data.push(newItem);
                }
            }

			// #ifdef H5
            data.Callback(hqChartData);
			// #endif
			
			// #ifndef H5
			data.Callback({data: hqChartData});
			// #endif

            this.SubscribRealtimeData(data);
        },

        //订阅最新日K线数据
        SubscribRealtimeData(data)   
        {
            //订阅最新数据
            var postData=this.GeneratePostData(data.OriginalSymbol,data.Period);

            var obj={SendData:postData.Sub, Symbol:data.Symbol, OriginalSymbol:data.OriginalSymbol, Period:data.Period };

            this.RequestWSData(obj, (recvData,data)=>{ this.RecvRealtimeData(recvData,data); });
        },

        RecvRealtimeData(recvData,data)
        {
            if (recvData.ch!=data.SendData.sub) return;
			if (!g_KLine.JSChart) return;

            var internalChart=g_KLine.JSChart.JSChartContainer;
            var period=internalChart.Period;
            var symbol=internalChart.Symbol;
            if (symbol!=data.Symbol || period!=data.Period) return;

            var hqChartData={code:0, stock:[]};
            //TODO:把recvData => hqchart内部格式 格式看教程
            //HQChart使用教程30-K线图如何对接第3方数据14-轮询增量更新日K数据
			
			if (this.Update.EnableLimit)	//是否启动缓存定时更新，降低刷新频率
			{
				var now=Date.now();
				if (this.Update.LastUpdateTime)
				{
					if (now-this.Update.LastUpdateTime<this.Update.Frequency) return;
				}
				
				this.Update.LastUpdateTime=now;
			}

            var stock={symbol:data.Symbol, name:data.OriginalSymbol};
            var item=recvData.tick;
            var dateTime = new Date();
            dateTime.setTime(item.id*1000);
            var date=dateTime.getFullYear()*10000+(dateTime.getMonth()+1)*100+dateTime.getDate();
            var time=dateTime.getHours()*100+dateTime.getMinutes();

            stock.date=date;
            stock.yclose=null;
            stock.open=item.open;
            stock.high=item.high;
            stock.low=item.low;
            stock.price=item.close;
            stock.vol=item.amount;
            stock.amount=null;

            hqChartData.stock.push(stock);
			
			// #ifdef H5
			internalChart.RecvRealtimeData(hqChartData);
			// #endif
			
			// #ifndef H5
			internalChart.RecvRealtimeData({data: hqChartData});
			// #endif
			
        },
		
		
		GeneratePostDepthData(symbol, step)
		{
			var reqData=
			{
				
			};
			
			var subData=
			{
				sub: `market.${symbol}.depth.${step}`,
				symbol: symbol
			};
			
			return { Req:reqData ,Sub:subData };
		},
		
		
		RequestDepthData(data, callback)
		{
			data.PreventDefault=true;
			this.Update.Cache=null;
			var symbol=data.Request.Data.symbol;
			var period=data.Self.Period;    //周期
			var postData=this.GeneratePostDepthData(this.OriginalSymbol,'step1');
			
			var obj={ SendData:postData.Sub , Symbol:symbol, OriginalSymbol:this.OriginalSymbol, Callback:callback };
			
			this.RequestWSData(obj, (recvData,data)=>{ this.RecvDepthData(recvData,data); });
		},
		
		
		RecvDepthData(recvData, data)
		{
			if (recvData.ch!=data.SendData.sub) return;
			
			if (!g_KLine.JSChart) return;
			
			var internalChart=g_KLine.JSChart.JSChartContainer;
			var symbol=internalChart.Symbol;
			if (symbol!=data.Symbol || internalChart.ClassName!='DepthChartContainer') return;
			
			var tick=recvData.tick;
			var asks=[], bids=[];
			
			if (tick.asks)
			{
				for(var i=0;i<tick.asks.length;++i)
				{
					var item=tick.asks[i];
					asks.push([item[0], item[1]]);
				}
			}
			
			if (tick.bids)
			{
				for(var i=0;i<tick.bids.length;++i)
				{
					var item=tick.bids[i];
					bids.push([item[0], item[1]]);
				}
			}
			
			var hqChartData=
			{ 
				code:0, 
				asks:asks,     //卖盘
				bids:bids,     //买盘 
				datatype:"snapshot"     //全量数据  
			}; 
			
			internalChart.ChartSplashPaint.EnableSplash(false);
			internalChart.RecvDepthData(hqChartData);
		},


		///////////////////////////////////////////////
		//手势事件 app/小程序才有
		//KLine事件
		KLineTouchStart: function (event) 
		{
		  if (g_KLine.JSChart) g_KLine.JSChart.OnTouchStart(event);
		},
		
		KLineTouchMove: function (event) 
		{
		  if (g_KLine.JSChart) g_KLine.JSChart.OnTouchMove(event);
		},
		
		KLineTouchEnd: function (event) 
		{
		  if (g_KLine.JSChart) g_KLine.JSChart.OnTouchEnd(event);
		},
	}
}
</script>

<style>
	
</style>
